	var p,fileName,canvas,tmpImage,client;
	var lastEvent = null;
	var lastAreaEvent = null;
	var ua = navigator.userAgent.toLowerCase();
	var isAndroid = ua.indexOf("android") > -1;	
	var numItems = 1;
	var realBinaryTransfer = false;
	var userList = {};
	var localUser = null;
	
	$(document).bind('pageinit',init);
	
	function onInitFs(fs) 
	{
	  alert('Opened file system: ' + fs.name);
	}

	function errorHandler(e) 
	{
	  var msg = '';

	  switch (e.code) {
		case FileError.QUOTA_EXCEEDED_ERR:
		  msg = 'QUOTA_EXCEEDED_ERR';
		  break;
		case FileError.NOT_FOUND_ERR:
		  msg = 'NOT_FOUND_ERR';
		  break;
		case FileError.SECURITY_ERR:
		  msg = 'SECURITY_ERR';
		  break;
		case FileError.INVALID_MODIFICATION_ERR:
		  msg = 'INVALID_MODIFICATION_ERR';
		  break;
		case FileError.INVALID_STATE_ERR:
		  msg = 'INVALID_STATE_ERR';
		  break;
		default:
		  msg = 'Unknown Error';
		  break;
	  };

	  console.log('Error: ' + msg);
	}
	
	function init()
	{
		canvas = document.createElement("canvas");
		tmpImage = document.createElement("img");
		
		try
		{
			/*
			window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
			window.requestFileSystem(window.TEMPORARY, 5*1024*1024 , onInitFs, errorHandler);
			*/
		
			client = new BinaryClient(serverBinary);
			client.on('open', clientOpen );
			client.on('stream', clientStream );
			client.on('error', function(error){
				alert(error);
			});
			client.on('close', function(){
				$("#divStatus").text("Desconectado");
			});
			//new webkit_draggable('exImg');
		}
		catch(e)
		{
			alert(e);
		}
	}
	
	function applyDragDrop()
	{	
		$( ".draggable" ).draggable();
		$( ".droppable" ).droppable();
		//$( ".resizable" ).resizable();
	}
	
	function clientOpen()
	{
		$("#divStatus").text("Conectado");
		$( ".shareable" ).live('vmousedown', function(e){
			dropped(e,null,false);
		});
		$('.shareArea').on('vmousedown', function(e){
			lastAreaEvent = e;
			var stream = client.send({},{method: 'clientWaiting'});
		});
		$('.shareArea').on('drop', function(e){  
			lastAreaEvent = e;
			lastEvent = e;
			dropped(e,null,typeof e.originalEvent.dataTransfer != 'undefined');
		});  
		$('.shareArea').on('dragenter', function(e){
		});
		applyDragDrop();
		client.send({},{method:'clientListRequest',value:'ALL'});
	}
	
	var audios = {};
	
	function clientStream(stream, meta)
	{
		if(meta)
		{
			if(meta.method=='recieveFile')
			{
				$("#divStatus").text("Recibiendo archivo");
				// Buffer for parts
				var parts = [];
				// Got new data
				if(realBinaryTransfer)
				{
					stream["metaInfo"] = meta;
					stream.on('data', function(data){
							parts.push(data);
					});
					stream.on('end', function(){
						console.debug(this["metaInfo"]);
						// Display new data in browser!
						var img = document.createElement("img");
						if(isAndroid)
						{
							var oBuilder = new BlobBuilder();
							oBuilder.append(parts);
							var oMyBlob = oBuilder.getBlob("image\/png"); // the blob
							img.src = (window.URL || window.webkitURL).createObjectURL(oMyBlob);
						}
						else
						{
							img.src = (window.URL || window.webkitURL).createObjectURL(new Blob(parts));
						}
						img.id = 'element'+(new Date()).getTime();
						img.zIndex = numItems++;
						img.width = 150;
						img.className = "box2d shareable draggable imageItem resizable";
						img.style.position = "absolute";
						img.style.display = "none";
						console.debug(lastAreaEvent);
						img.style.top = ((typeof lastAreaEvent.clientY == 'undefined'? lastAreaEvent.originalEvent.layerY : lastAreaEvent.clientY) - img.height/2)+'px';
						img.style.left = ((typeof lastAreaEvent.clientX == 'undefined'? lastAreaEvent.originalEvent.layerX : lastAreaEvent.clientX) - img.width/2)+'px';
						//document.body.appendChild(img);
						$("#face1").append(img);
						$(img).show('pulsate',200,function(){
								setGravityBySelector('#'+img.id);
								//new webkit_draggable(img.id);
								//applyDragDrop();
						});
					});
				}
				else
				{
					var fileExt = meta.fileExt;
					switch(fileExt)
					{
						case "jpg":
						case "gif":
						case "png":
							var curNode = document.createElement("img");
							curNode["meta"] = meta;
							curNode.width = 150;
							curNode.className = "box2d shareable draggable imageItem resizable";
							curNode.style.position = "absolute";
							curNode.zIndex = numItems++;
							if(lastAreaEvent != null)
							{
								curNode.style.top = ((typeof lastAreaEvent.clientY == 'undefined'? lastAreaEvent.originalEvent.layerY : lastAreaEvent.clientY) - curNode.height/2)+'px';
								curNode.style.left = ((typeof lastAreaEvent.clientX == 'undefined'? lastAreaEvent.originalEvent.layerX : lastAreaEvent.clientX) - curNode.width/2)+'px';
							}
							else
							{
								curNode.style.top = window.innerHeight/2;
								curNode.style.left = window.innerWidth/2;
							}
							curNode.src = meta.imageUrl;
							curNode.id = 'element'+(new Date()).getTime();
							curNode.style.display = "none";
							$(curNode).bind('dblclick',function(e){
								location.href = meta.url;
							});
							$(curNode).bind('taphold',function(e){
								location.href = meta.url;
							});
							
							$("#face1").append(curNode);
							$(curNode).show('pulsate',200,function(){
									setGravityBySelector('#'+curNode.id);
							});
							break;
						case "wav":
						case "mp3":
						case "ogg":
							var idElem  = (new Date()).getTime();
							var audioNode = document.createElement("audio");
							audioNode.src = meta.url;
							audioNode.id = 'audio_'+idElem;
							audioNode.play();
							audios[audioNode.id] = audioNode;
							var curNode = document.createElement("img");
							curNode["meta"] = meta;
							curNode.width = 150;
							curNode.className = "box2d shareable draggable imageItem resizable";
							curNode.style.position = "absolute";
							curNode.zIndex = numItems++;
							if(lastAreaEvent != null)
							{
								curNode.style.top = ((typeof lastAreaEvent.clientY == 'undefined'? lastAreaEvent.originalEvent.layerY : lastAreaEvent.clientY) - curNode.height/2)+'px';
								curNode.style.left = ((typeof lastAreaEvent.clientX == 'undefined'? lastAreaEvent.originalEvent.layerX : lastAreaEvent.clientX) - curNode.width/2)+'px';
							}
							else
							{
								curNode.style.top = window.innerHeight/2;
								curNode.style.left = window.innerWidth/2;
							}
							curNode.src = meta.imageUrl;
							curNode.id = 'element_'+idElem;
							console.debug('element_'+idElem);
							curNode.style.display = "none";
							
							$(curNode).bind('vmousedown',function(e){
								var numId = e.target.id.split('_').pop();
								console.debug('audio_'+numId);
								audios['audio_'+numId].play();
							});
							$(curNode).bind('dblclick',function(e){
								location.href = meta.url;
							});
							$(curNode).bind('taphold',function(e){
								location.href = meta.url;
							});
							
							$("#face1").append(curNode);
							
							$(curNode).show('pulsate',200,function(){
									setGravityBySelector('#'+curNode.id);
									audioNode.play();
							});
							break;
						default:
							var idElem  = (new Date()).getTime();
							var curNode = document.createElement("img");
							curNode["meta"] = meta;
							curNode.width = 150;
							curNode.className = "box2d shareable draggable imageItem resizable";
							curNode.style.position = "absolute";
							curNode.zIndex = numItems++;
							if(lastAreaEvent != null)
							{
								curNode.style.top = ((typeof lastAreaEvent.clientY == 'undefined'? lastAreaEvent.originalEvent.layerY : lastAreaEvent.clientY) - curNode.height/2)+'px';
								curNode.style.left = ((typeof lastAreaEvent.clientX == 'undefined'? lastAreaEvent.originalEvent.layerX : lastAreaEvent.clientX) - curNode.width/2)+'px';
							}
							else
							{
								curNode.style.top = window.innerHeight/2;
								curNode.style.left = window.innerWidth/2;
							}
							curNode.src = meta.imageUrl;
							curNode.id = 'element_'+idElem;
							console.debug('element_'+idElem);
							curNode.style.display = "none";
							
							$(curNode).bind('dblclick',function(e){
								location.href = meta.url;
							});
							$(curNode).bind('taphold',function(e){
								location.href = meta.url;
							});
							
							$("#face1").append(curNode);
							
							$(curNode).show('pulsate',200,function(){
									setGravityBySelector('#'+curNode.id);
							});
							break;
					}
				}
			}
			else if(meta.method=='clientWaiting')
			{
				$("#divStatus").text("El servidor sabe que estamos esperando");
			}
			else if(meta.method=='serverWaiting')
			{
				$("#divStatus").text("Ya me pidieron el archivo pero nadie lo esta esperando");
			}
			else if(meta.method=='sendRequest')
			{
				$("#divStatus").text("Ya alguien pidio el archivo que estaba pendiente");
				dropped(lastEvent,meta.value,false);
			}
			else if(meta.method=='connectedTo')
			{
				$("#divStatus").text("Hay un archivo para mi que me pasaran");
			}
			else if(meta.method=='userConnected')
			{
				$("#divStatus").text("New user "+meta.value+" is connected :)");
				updateUserList("add",meta.value);
				drawUsers();
			}
			else if(meta.method=='userDisconnected')
			{
				$("#divStatus").text("The user "+meta.value+" is disconnected :( ");
				updateUserList("remove",meta.value);
				drawUsers();
			}
			else if(meta.method=='clientListResponse')
			{
				$("#divStatus").text("Users connected are this: "+meta.value);
				localUser = meta.user;
				$("#localUserId").text(localUser);
				updateUserList("list",meta.value);
				drawUsers();
			}
		}
	}
	
	var boxes = ["leftBox","rightBox","bottomBox","topBox"];
	var users = [null,null,null,null];
	
	function drawUsers()
	{
		var j = 0;
		users = [null,null,null,null];
		for(var i in boxes)
		{
			$("#"+boxes[i]).text("");
		}
		for(var i in userList)
		{
			if(j<4)
			{
				if(i!=localUser)
				{
					$("#"+boxes[j]).text(i);
					users[j] = i;
					j++;
				}
			}
			else
			{
				break;
			}
		}
	}
	
	function updateUserList(action,user)
	{
		switch(action)
		{
			case "add":
				userList[user] = true;
				break;
			case "remove":
				delete userList[user];
				break;
			case "list":
				if(user)
				{
					var arrUser = user.split(',');
					for(var i in arrUser)
					{
						userList[arrUser[i]] = true;
					}
				}
				break;
		}
		console.debug(userList);
	}
	
	function getFileExt(filename)
	{
		return filename.split('.').pop();
	}
	
	function dropped(e,extra,external)
	{
		if(e)
		{
			lastEvent = e;
			var file;
			var fileSize = 0;
			var fileUrl = false;
			var imageUrl = false;
			var fileExt = "";
			if(typeof e.originalEvent != 'undefined')
			{
				e.originalEvent.preventDefault();
				if(typeof e.originalEvent.dataTransfer != 'undefined')
				{
					if(e.originalEvent.dataTransfer  != null )
					{
						file = e.originalEvent.dataTransfer.files[0];
						fileName = file.name;
						fileSize = file.size;
						fileExt = getFileExt(fileName);
					}
					else
					{
						if(realBinaryTransfer)
						{
							file = imageToBlob(e.srcElement);
							fileName = file.name;
							fileSize = file.size;
							fileExt = getFileExt(fileName);
						}
						else
						{
							file = {};
							fileName = e.srcElement["meta"]["fileName"];
							fileUrl = e.srcElement["meta"]["url"];
							fileExt = e.srcElement["meta"]["fileExt"];
							imageUrl = e.srcElement["meta"]["imageUrl"];
						}
					}
				}
				else
				{
					if(typeof e.srcElement != 'undefined')
					{
						if(realBinaryTransfer)
						{
							file = imageToBlob(e.srcElement);
							fileName = file.name;
							fileSize = file.size;
						}
						else
						{
							file = {};
							fileName = e.srcElement["meta"]["fileName"];
							fileUrl = e.srcElement["meta"]["url"];
							fileExt = e.srcElement["meta"]["fileExt"];
							imageUrl = e.srcElement["meta"]["imageUrl"];
						}
					}
				}
			}
			else
			{
				if(realBinaryTransfer)
				{
					file = imageToBlob(e);
					fileName = file.name;
					fileSize = file.size;
				}
				else
				{
					file = {};
					fileName = e["meta"]["fileName"];
					fileUrl = e["meta"]["url"];
					fileExt = e["meta"]["fileExt"];
					imageUrl = e["meta"]["imageUrl"];
				}
			}
			// `client.send` is a helper function that creates a stream with the 
			// given metadata, and then chunks up and streams the data.
			$("#divStatus").text("Enviando archivo");
			var stream = client.send(file, {method: 'sendFile', name: fileName, size: fileSize, extra: extra, external: external, fileUrl:fileUrl, fileExt:fileExt, imageUrl:imageUrl });
			
			// Print progress
			var tx = 0;
			stream.on('data', function(data){
			  $('#progress').text(Math.round(tx+=data.rx*100) + '% complete');
			});
		}
	}
	
	function imageToBlob(image)
	{ 
		tmpImage.setAttribute('src', image.src); 
		canvas.width = tmpImage.width; 
		canvas.height = tmpImage.height; 
		var ctx = canvas.getContext("2d"); 
		ctx.drawImage(tmpImage, 0, 0); 
		var base64Object = canvas.toDataURL("image/png");  
		var blobObject = base64ToBlob(base64Object);
		return blobObject;
	} 
	
	function base64ToBlob(dataURI) 
	{
		// convert base64 to raw binary data held in a string
		// doesn't handle URLEncoded DataURIs
		var byteString = atob(dataURI.split(',')[1]);

		// separate out the mime component
		var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

		// write the bytes of the string to an ArrayBuffer
		
		/*
		var ab = new ArrayBuffer(byteString.length);
		var ia = new Uint8Array(ab);
		for (var i = 0; i < byteString.length; i++) {
			ia[i] = byteString.charCodeAt(i);
		}

		// write the ArrayBuffer to a blob, and you're done
		
		var bb = new BlobBuilder();
		bb.append(ab);
		return bb.getBlob(mimeString);
		*/

		var ia = new Uint8Array(byteString.length);
		for (var i = 0; i < byteString.length; i++) {
			ia[i] = byteString.charCodeAt(i);
		}

		var exitBlob;
		if(isAndroid)
		{
			var oBuilder = new BlobBuilder();
			oBuilder.append(ia.buffer);
			exitBlob = oBuilder.getBlob("image\/png"); // the blob
		}
		else
		{
			exitBlob = new Blob([ia.buffer], {type: mimeString});
		}
		
		return exitBlob;
		
	}